package com.scalar.chiptrack.reports.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.db.DataSource;
import com.scalar.chiptrack.jasper.base.JasperReportsHelper;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.HashMap;

/**
 *
 */
public class GenericJasperReportActionCommand extends ActionCommand {
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String action = request.getParameter(REQUEST_PARAM_ACTION);
        String reportName = request.getParameter(REQUEST_PARAM_REPORT_NAME);
        String reportType = request.getParameter(REQUEST_PARAM_REPORT_TYPE);
        ServletContext context = request.getSession().getServletContext();

        File reportFile = new File(context.getRealPath("/jasper_reports/jasper" + (reportName.startsWith("/") ? reportName : "/"+reportName) + ".jasper"));
        if (!reportFile.exists()) {
            throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");
        }

        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile.getPath());

        Map<Object, Object> parameters = new HashMap<Object, Object>();
        parameters.putAll(request.getParameterMap());
        Connection conn = null;
        JasperPrint jasperPrint = null;
        try {
            conn = DataSource.getConnection();
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ignore) {
                    ignore.printStackTrace();
                }
            }
        }
        JasperReportsHelper.exportReport(jasperPrint, request, response);
        return null;
    }
}
